package com.film.service.imp;
import com.film.mapper.UserMapper;
import com.film.pojo.User;
import com.film.service.UserService;
import com.film.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImp implements UserService {
   private String dir="G:/image";
   private String urlDir="/image.film.com";
    @Autowired
    private UserMapper userMapper;
    @Transactional
    @Override
    public boolean updateUser(User user) {
        boolean bl=userMapper.updateUser(user);
        return bl;
    }


    @Transactional
    @Override
    public Boolean updateAvatar(MultipartFile file,Integer id) {
        String fileName=file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(png|jpg|gif)$")){
            return false;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int heigth = bufferedImage.getHeight();
            if(width==0||heigth==0){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        File dirFile=new File(dir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String uuid=UUID.randomUUID().toString().replace("-", "");
        int i=fileName.lastIndexOf(".");
        String newFileName=uuid+fileName.substring(i);
        String path1=dir+"/"+newFileName;
        String path=urlDir+"/"+newFileName;
        try {
            file.transferTo(new File(path1));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return userMapper.updateAvatar(path,id);
    }

    @Override
    public User userLogin(User user) {
        User user1=userMapper.userLogin(user);
        if(user.getPassword().equals(user1.getPassword())){
            return user1;
        }
        return null;
    }

    @Override
    public User getUserInfo(Integer id) {
        User user=userMapper.getUserInfo(id);
        return user;
    }

    @Override
    public boolean saveUserInfo(User user) {
        boolean bl=userMapper.saveUserInfo(user);
        return bl;
    }
}
